<?php
namespace app\hotel\controller;

use app\common\controller\Hotel;
use app\common\model\Coupon\Coupon as CouponCoupon;
use app\common\model\Coupon\Receive;
use think\Request;
use Exception;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

class Coupon extends Hotel
{
    protected $model = null;
    public function __construct(Request $request)
    {
        $this->noLogin = ['*','receive','available'];
        parent::__construct($request);
        $this->model = new CouponCoupon();
    }
    public function index()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $result = $this->isLogin();
        $status = $this->request->get('status')??0;
        $page = $this->request->get('page')??1;
        $pageSize = $this->request->get('pageSize')??6;
        $where = [];
        if($result['code']){
            $busid = $this->business['id'];
            $receiveWhere = ['busid'=>$busid];
            $receiveList = Receive::with(['coupon'])->where($receiveWhere)->select();
            $receiveStatus = [];
            foreach($receiveList->all() as $receive){
                $receiveStatus[$receive['cid']] = $receive['status'];
            }
            $couponList = [];
            switch($status){
                case 0:
                    $where = [];
                    $couponList = $this->model->where($where)->paginate($pageSize,$page);
                    break;
                case 1:
                    $where = ['status'=>'0','endtime'=>['<=',time()]];
                    $couponList = $this->model->where($where)->paginate($pageSize,$page);
                    break;
                case 2:
                    $couponList = Receive::with(['coupon'])->where($receiveWhere)->paginate($pageSize,$page);
                    foreach ($couponList as $key => $item) {
                        // 这里的 $item 代表每一条记录的数组
                        // 进行你需要的修改操作
                        $item = $item['coupon'];
                        // 保存修改后的值回到 Paginator 对象中
                        $couponList->offsetSet($key, $item);
                    }
                    break;
                case 3:
                    $receiveWhere['receive.status'] = '1';
                    $couponList = Receive::with(['coupon'])->where($receiveWhere)->paginate($pageSize,$page);
                    foreach ($couponList as $key => $item) {
                        // 这里的 $item 代表每一条记录的数组
                        // 进行你需要的修改操作
                        $item = $item['coupon'];
                        // 保存修改后的值回到 Paginator 对象中
                        $couponList->offsetSet($key, $item);
                    }
                    break;
            }
            foreach ($couponList as $key => $item) {
                if($item['total']<=0){
                    $item['s'] = '6';//已领完
                    $couponList->offsetSet($key, $item);
                    continue;
                }
                // 这里的 $item 代表每一条记录的数组
                // 进行你需要的修改操作
                if(in_array($item['id'],array_keys($receiveStatus))){
                    if($receiveStatus[$item['id']]=='1'){
                        if($item['status']=='1'){
                            $item['s'] = 1;//已领取 未使用 未结束（可使用）
                        }else{
                            $item['s'] = 2;//已领取 未使用 已结束（已过期）
                        }
                    }else{
                        $item['s'] = 3;//已领取 已使用（已使用）
                    }
                }else{
                    if($item['status']=='1'){
                        $item['s'] = 4;//未领取 未结束（可领取）
                    }else{
                        $item['s'] = 5;//未领取 已结束（已结束）
                    }
                }
                // 保存修改后的值回到 Paginator 对象中
                $couponList->offsetSet($key, $item);
            }
            $this->success('',null,$couponList);
        }else{
            switch($status){
                case 0:
                    $where = [];
                    break;
                case 1:
                    $where = ['status'=>'0','endtime'=>['<=',time()]];
                    break;
                case 2:
                case 3:
                    $this->result([],404,'未登录');
            }
            $couponList = $this->model->where($where)->paginate($pageSize,$page);
            $this->success('',null,$couponList);
        }
    }
    public function receive()
    {
        if(!$this->request->isPost())$this->error('请求错误');
        $receiveModel = new Receive();
        $cid = $this->request->post('cid');
        $coupon = $this->model->get($cid);
        if(!$coupon)$this->error('找不到优惠券');
        if($coupon['total']<=0)$this->error('已领完');
        $busid = $this->business['id'];
        $params = ['busid'=>$busid,'cid'=>$cid];
        $receive = $receiveModel->where($params)->find();
        if($receive)$this->error('已领取过');
        $result = null;
        Db::startTrans();
        try {
            $coupon['total']-=1;
            $coupon->isUpdate()->save();
            $params['status'] = '1';
            $result = $receiveModel->create($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $result?$this->success('领取成功'):$this->error('领取失败');
    }
    public function info()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $cid = $this->request->get('cid');
        $coupon = $this->model->get($cid);
        if(!$coupon)$this->error('找不到优惠券');
        if($coupon['total']<=0){
            $coupon['s'] = '6';
            $this->success('',null,$coupon);
        }
        $result = $this->isLogin();
        if($result['code']){
            $busid = $this->business['id'];
            $receiveWhere = ['busid'=>$busid];
            $receiveList = Receive::with(['coupon'])->where($receiveWhere)->select();
            $receiveStatus = [];
            foreach($receiveList->all() as $receive){
                $receiveStatus[$receive['cid']] = $receive['status'];
            }
                // 这里的 $item 代表每一条记录的数组
                // 进行你需要的修改操作
            if(in_array($coupon['id'],array_keys($receiveStatus))){
                if($receiveStatus[$coupon['id']]=='1'){
                    if($coupon['status']=='1'){
                        $coupon['s'] = 1;//已领取 未使用 未结束（可使用）
                    }else{
                        $coupon['s'] = 2;//已领取 未使用 已结束（已过期）
                    }
                }else{
                    $coupon['s'] = 3;//已领取 已使用（已使用）
                }
            }else{
                if($coupon['status']=='1'){
                    $coupon['s'] = 4;//未领取 未结束（可领取）
                }else{
                    $coupon['s'] = 5;//未领取 已结束（已结束）
                }
            }
            // 保存修改后的值回到 Paginator 对象中
        }
        $this->success('',null,$coupon);
    }
    public function received()
    {
        $receiveModel = new Receive();
        $cid = $this->request->get('cid',0);
        $where = ['cid'=>$cid];
        return $receiveModel->where($where)->select();
    }
    public function available()
    {
        $busid = $this->business['id'];
        $receiveModel = new Receive();
        $where = ['busid'=>$busid,'receive.status'=>'1'];
        return $receiveModel->with(['coupon'])->where($where)->select()->column('coupon');
    }
    public function showCoupon()
    {
        return $this->model->where('status','1')->order('createtime','desc')->limit(4)->select();
    }
}
